package com.zjj.learn.designmodel.pattern.singleton.demo7;

import java.io.Serializable;

/** 通过序列化和反序列化破坏单例模式
 * *** @author zjj_admin
 * *** 2022/4/5 16:08
 */
public class Singleton implements Serializable {

    private Singleton(){}

    //定义一个静态内部类，内部定义当前类的静态属性
    private static class SingletonHolder{
        private static final Singleton instance = new Singleton();
    }

    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }

    /**
     * 添加这个方法可以防止反序列化破坏单例模式
     * @return
     */
    private Object readResolve(){
        return SingletonHolder.instance;
    }
}
